Ext.ns("CRM.SPComp");

(function(){
	   
	var oppValidationFormIds = ["opportunityTitle","dealSize","oppClosingProbability","salesPerson","stage",
	         	                "createDate","status","targetDate","actualCloseDate","opportunityDiscription"];
	
	var leadOppCmpIds = ["opportunityTitle","dealSize","oppClosingProbability","salesPerson","stage",
    	                 "createDate","status","targetDate","actualCloseDate","opportunityDiscription"];

	
    var win;
    
	CRM.SPComp.showOpportunityWindow = function (leadId,opportunityId,rowdata){
		
        var confidencelevelStore = CRM.commons.createComboStore('confidencelevelStoreid','opportunity/opportunityReqCombo','confidencelevelTypes');
		var oppstageStore = CRM.commons.createComboStore('oppStageStoreid','opportunity/opportunityReqCombo','stageTypes');
		var statusStore = CRM.commons.createComboStore('statusStoreid','opportunity/opportunityReqCombo','statusTypes');
        var salespersonStore = CRM.commons.createComboStore('salespersonStoreid','opportunity/salespersonTypes','');
		
		var opportunityPanel = {
                xtype       : 'fieldset',
                id          : 'opportunityPanel',
                title       : 'Opportunity Information',
                width       : 580,
                height      : 330,
                layout      : 'form',
                labelWidth  : 140,
                items       : [ 
                               {
                                 xtype:'hidden',
                                 id   :'oppLeadId',
                                 value:leadId
                                },
                                { 
                                  xtype   : 'hidden',
                                  id      : 'opportunityId',
                                  value   : opportunityId
                                },
                                {
                                  xtype      : 'textfield',
                                  fieldLabel : 'Opportunity Title<font color=red>*</font>',
                                  id         : 'opportunityTitle',
                                  name       : 'opportunityTitle',
                                  width      : 325,
                                  allowBlank : false
                                },
                                {
                                  xtype      : 'numberfield',
                                  fieldLabel : 'Deal Size<font color=red>*</font>',
                                  id         : 'dealSize',
                                  name       : 'dealSize',
                                  width      :  130,
                                  allowBlank : false
                                },
                                {
									xtype        : 'combo',
								    fieldLabel   : 'Closing Probability<font color=red>*</font>',
								    id	         : 'oppClosingProbability',
								    valueField   : 'id',
								    value        :'SELECT',
									store        : confidencelevelStore,
									displayField : 'name',
									triggerAction: 'all',
									value        : 'SELECT',
									typeAhead    : false,
									editable     : false,
									width        : 325,
									listeners	: {select : function(){
			    											bindValue('oppClosingProbability', 'oppClosingProbabilityId');
			    										} 
                                				  }
								},
								{
									xtype		: 'hidden',
									id			: 'oppClosingProbabilityId'
								},
								{
								    xtype        : 'combo',
								    fieldLabel   : 'Sales Person<font color=red>*</font>',
								    id           : 'salesPerson',
								    valueField   : 'id',
								    value        :'SELECT',
								    store        : salespersonStore,
								    displayField : 'name',
								    triggerAction: 'all',
								    value        : 'SELECT',
								    typeAhead    : false,
								    editable     : false,
								    width        : 325,
								    listeners	: {select : function(){
		        											bindValue('salesPerson', 'salesPersonId');
		        											} 
												  }
								   },
								  {
								    	xtype		: 'hidden',
								    	id			: 'salesPersonId'
								  },
                                  {
                                    xtype     : 'compositefield',
                                    fieldLabel: 'Stage<font color=red>*</font>',
                                    items     : [
                                                 {
                                                         xtype        : 'combo',
                                                         id           : 'stage',
                                                         //hiddenName   : 'stageHiddenName',
                                                         valueField   : 'id',
                                                         value        :'SELECT',
                                                         store        : oppstageStore,
                                                         displayField : 'name',
                                                         triggerAction:'all',
                                                         value        : 'SELECT',
                                                         typeAhead    : false,
                                                         editable     : false,
                                                         width        : 130,
                                                         listeners	: {select : function(){
					                    									bindValue('stage', 'stageId');
					                    									} 
					                    			  					}
										              },
										              {
										                	xtype		: 'hidden',
										                	id			: 'stageId'
										              },
                                                      {  xtype    :'displayfield',value : 'Create Date<font color=red>*</font>:'},
                                                      {
                                                         xtype    : 'datefield',
                                                         id       : 'createDate',
                                                         name     : 'createDate',
                                                         vtype    : 'daterange',
                                                         endDateField: 'targetDate',
                                                         format   : 'Y-m-d',
                                                         width    : 120
                                                      }
                                                  
                                                ]
                                },
                                {
                                    xtype     : 'compositefield',
                                    fieldLabel: 'Status<font color=red>*</font>',
                                    items     : [
                                                  {
                                                         xtype        : 'combo',
                                                         id           : 'status',
                                                         //hiddenName   : 'statusHiddenName',
                                                         store        : statusStore,
                                                         displayField : 'name',
                                                         valueField   : 'id',
                                                         value        :'SELECT',
                                                         triggerAction: 'all',
                                                         typeAhead    : false,
                                                         editable     : false,
                                                         width    	  : 130,
                                                         listeners	: {select : function(){
					                    						bindValue('status', 'statusId');
					                    					} 
					                    			  }
									                },
									                {
									                	xtype		: 'hidden',
									                	id			: 'statusId'
									                },
                                                      {
                                                          xtype : 'displayfield',
                                                          value : 'Target Date<font color=red>*</font>:'
                                                       },
                                                       {
                                                          xtype : 'datefield',
                                                          id    : 'targetDate',
                                                          name  : 'targetDate',
                                                          format: 'Y-m-d',
                                                          width : 120
                                                       }]
                                },
                                {
                                  xtype      : 'datefield',
                                  fieldLabel : 'Actual Close Date<font color=red>*</font>',
                                  id         : 'actualCloseDate',
                                  name       : 'actualCloseDate',
                                  format     : 'Y-m-d',
                                  width      : 130
                                },
                                {
                                  xtype      : 'textfield',
                                  fieldLabel : 'Description<font color=red>*</font>',
                                  id         : 'opportunityDiscription',
                                  name       : 'opportunityDiscription',
                                  width      : 325
                                }
                              ]
            };

            var oppRootPanel = new Ext.FormPanel({
                id          : 'oppRootPanel',
                height      : 650,
                width       : 1350,
                frame       : false,
                layout      : 'hbox',
                items       : [opportunityPanel],
                bbar        : {
            	                  xtype       : 'toolbar',buttonAlign : 'right',
            	                  items       : [{
												    xtype   : 'button',
												    id		: 'addButton',
												    text    : 'Save',
												    handler : function(){
            	                	                                var actionValue = Ext.getCmp('addButton').getText();
            	                	                                ValidateAndSaveOpportunity(actionValue,oppRootPanel);
												    				//addOpportunity(actionValue,oppRootPanel);
												    			}
												 },'-',
												 {
						                                xtype   : 'button',
						                                id		: 'cancelButton',
						                                text    : 'Cancel',
						                                handler	: closeOpportunityWindow
						                         }]
                    }
            });

		
        	    win = new Ext.Window({
        		   id     : 'oppWindow',
        		   title  : 'Create New Opportunity',
        		   width  : 600,
        		   height : 400,
        		   layout : 'fit',
        		   border : true,
               	   plain  : false,
                   closable    : true,
               	   collapsible : true,
               	   animCollapse: true,
               	   draggable   : true,
               	   maximizable : false,
               	   onEsc	   : true,
               	   model	   : true,
               	   items       : [oppRootPanel]
               	});
        	 
        		
        		if(rowdata != null){
                	Ext.getCmp('addButton').setText('Update');
                	showOpportunityDetails(rowdata,oppRootPanel);
             }
        		win.show(this);
        		validateFormOnLoad(oppRootPanel, oppValidationFormIds);
        		return win; 
        	};
        	
        	 //Date Validation
            Ext.apply(Ext.form.VTypes, {
    		daterange : function(val, field) {
    			var date = field.parseDate(val);
    	 
    			if(!date){
    				return;
    			}
    			if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
    				var start = Ext.getCmp(field.startDateField);
    				start.setMaxValue(date);
    				start.validate();
    				this.dateRangeMax = date;
    			} 
    			else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
    				var end = Ext.getCmp(field.endDateField);
    				end.setMinValue(date);
    				end.validate();
    				this.dateRangeMin = date;
    			}
    			return true;
    		}
    	});
            	
        	
        	
        	 function ValidateAndSaveOpportunity(action,formPanel){
	             //var form = Ext.getCmp('mainPanel');
	 			 var validationSuccess = simpleFormValidation(formPanel, oppValidationFormIds);
	 			 	if(validationSuccess == 'true'){
	 			 		addOpportunity(action,formPanel);
	 				}
           	 };
        	
        	function addOpportunity(action,formPanel) {
	        		//var formPanel = Ext.getCmp('oppRootPanel');
          	        var values = formPanel.getForm().getValues();
          	        var encoded = Ext.encode(values);
          	        
          	        Ext.Ajax.request({
          	        	   url      : 'lead/saveOpportunity?action='+action,
          	        	   method   : 'POST', 
          	        	   success	: function(result, request){
				  			  			var jsonData = Ext.util.JSON.decode(result.responseText); 
				  			  			var responsedOpportunityId = jsonData.data;
				  			  			
				  			  			var selectedId = null;
			      			   		    if(Ext.getCmp('leadId') != null){
			      			   		    	var selectedLeadId = Ext.getCmp('leadId').getValue();
			      			   		    	var oppGrd = Ext.getCmp('opportunitiesGrid');
			      			   		    	reloadLeadSubTabs(oppGrd, selectedLeadId);
			      			   		    }
			      			   		    if(Ext.getCmp('customerId') != null){
			      			   		    	var selectedCustomerId = Ext.getCmp('customerId').getValue();
			      			   		    	var oppGrd = Ext.getCmp('opportunitiesGrid');
			      			   		    	reloadCustomerSubTabs(oppGrd, selectedCustomerId);
			      			   		    }
				  			   			//showOpportunities();   //this method is in lead.js and customer.js with same name
				  			   		    closeOpportunityWindow();
			  			   		  	  },
          	        	   failure  : function() { 
          	        		   			alert ("failure"); 
          	        		   			},
          	        	   jsonData : encoded  
          	        	});
          	};
        	

        	function closeOpportunityWindow(){
    			win.close();
    		}
        	
        	
        	function showOpportunityDetails(rowdata,oppRootPanel){
        		var leadGrid = Ext.getCmp('spSearchLeadGridPanel');
	 			var customerGrid = Ext.getCmp('spSearchCustomerGridPanel');
		 		if(leadGrid != null){
	        		var leadId = Ext.getCmp('leadId').getValue();
	        		Ext.getCmp('oppLeadId').setValue(leadId);
	 			}
		 		if(customerGrid != null){
		 			var customerId = Ext.getCmp('customerId').getValue();
	        		Ext.getCmp('oppLeadId').setValue(customerId);
		 		}
		 		Ext.getCmp('opportunityId').setValue(rowdata.get('id'));
		 		
		 	
		 		oppRootPanel.getForm().loadRecord(rowdata);
			}	
        	
        
        	
})();

